from telethon import TelegramClient
from telethon.errors import SessionPasswordNeededError
from config import API_HASH, API_ID, LOGIN_TYPE, PHONE, SESSION_NAME
from utils.logger import setup_logger

logger = setup_logger(__name__)

class LoginManager:
    def __init__(self) -> None:
        print(f"[DEBUG] 进入函数: LoginManager.__init__")
        self.client = TelegramClient(
            SESSION_NAME,
            API_ID,
            API_HASH,
            connection_retries=None,
            auto_reconnect=True
        )

    async def login(self) -> bool:
        print(f"[DEBUG] 进入函数: LoginManager.login")
        await self.client.connect()
        if await self.client.is_user_authorized():
            me = await self.client.get_me()
            logger.info("已登录 user_id=%s", me.id)
            return True
        
        if LOGIN_TYPE == "phone":
            await self.client.send_code_request(PHONE)
            code = input("验证码：")
            try:
                await self.client.sign_in(PHONE, code)
            except SessionPasswordNeededError:
                pwd = input("2FA 密码：")
                await self.client.sign_in(password=pwd)
            return True
        logger.error("session 文件不存在，请先手机登录一次")
        return False